package com.adopapa.nezhacloud.register.conf;

import java.io.IOException;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

//@WebFilter(urlPatterns = "/**", filterName = "AuthFilter")
public class AuthFilter implements Filter {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		try {
			HttpServletResponse resp = (HttpServletResponse) response;
			HttpServletRequest req = (HttpServletRequest) request;

			logger.info(((HttpServletRequest) request).getHeader("Origin"));
			logger.info(req.getMethod());

			resp.addHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
			// ((HttpServletResponse)
			// response).setHeader("Access-Control-Allow-Origin",
			// ((HttpServletRequest) request).getHeader("Origin"));
			resp.addHeader("Access-Control-Allow-Methods", "GET,OPTION,OPTIONS,PUT,POST,DELETE");
			resp.addHeader("Access-Control-Allow-Headers",
					"Origin,X-Requested-With, Content-Type, Accept, loginTicket, agentId");
			// ((HttpServletResponse)
			// response).setHeader("Access-Control-Max-Age",
			// "3600");
			resp.addHeader("Access-Control-Allow-Credentials", "true"); // 是否支持cookie跨域
			resp.addHeader("XDomainRequestAllowed", "1");
//
//			if ("OPTIONS".equalsIgnoreCase(req.getMethod())) {
//				resp.setStatus(204);
//			}
		} catch (Exception e) {
			logger.error(ExceptionUtils.getStackTrace(e));

		}

		chain.doFilter(request, response);

	}

}
